/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.scene.mapper.ProjectSafetyMeetingMapper;
import com.koron.scene.service.api.ProjectSafetyMeetingService;
import com.koron.scene.utils.BusinessCode;
import com.koron.scene.utils.ExcelUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;

import java.util.*;

@SuppressWarnings("deprecation")
@Service
public class ProjectSafetyMeetingServiceImpl implements ProjectSafetyMeetingService {
    private final static  Logger logger = LoggerFactory.getLogger(ProjectSafetyMeetingServiceImpl.class);

    @Override
    public MessageBean<?> importExcel(StaffBean user, MultipartFile file, String projectId, String enterpriseId) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        SessionFactory factory = null;
        try {
            List<String> keys = Arrays.asList("meetingName","meetingTitle","meetingAddress","meetingUserName","meetingTimeStart",
                    "meetingTimeStop","meetingJoinUsers","meetingContext","managerName","remark");
            List<Map> list = analysisXlsx(file, 2, 0, 9, keys);
            // 参数处理
            if (list != null && list.size() > 0){
                Date date = new Date();
                String userCode = user.getCode();
                String userName = user.getName();
                for (Map map : list){
                    map.put("id", DefaultIdGenerator.getInstance().generateLongId());
                    map.put("projectId", projectId);
                    map.put("enterpriseId", enterpriseId);
                    map.put("addUser", userCode);
                    map.put("addUserName", userName);
                    map.put("addTime", date);
                    map.put("updateUser", userCode);
                    map.put("updateUserName", userName);
                    map.put("updateTime", date);
                    // 会议发起人
                    map.put("meetingUser", map.get("meetingUserName"));
                    // 会议发起人
                    map.put("manager", map.get("managerName"));
                }
                factory = new SessionFactory();
                ProjectSafetyMeetingMapper mapper = factory.getMapper(ProjectSafetyMeetingMapper.class);
                mapper.insertProSafetyMeeting(list);
            }
            if (factory != null){
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (factory != null){
                factory.close(false);
            }
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription("导入安全会议失败，请检查数据格式!");
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean queryForList(String meetingName, String projectId, String enterpriseId, Integer page, Integer pageSize) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            ProjectSafetyMeetingMapper mapper = factory.getMapper(ProjectSafetyMeetingMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("meetingName", meetingName);
            map.put("projectId", projectId);
            map.put("enterpriseId", enterpriseId);
            page = (page == null || page < 1) ? 1 : page;
            pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
            int pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageStop", pageSize);
            List<Map> list = mapper.queryForList(map);
            DataBean<Map> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            // 总条数
            Integer totalNumber = mapper.countQueryForList(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public List<Map> exportForList(String meetingName, String projectId, String enterpriseId) {
        List<Map> list = null;
        try (SessionFactory factory = new SessionFactory()){
            ProjectSafetyMeetingMapper meetingMapper = factory.getMapper(ProjectSafetyMeetingMapper.class);
            list = meetingMapper.exportForList(meetingName, projectId, enterpriseId);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    @Override
    public MessageBean deleteById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ProjectSafetyMeetingMapper mapper = factory.getMapper(ProjectSafetyMeetingMapper.class);
            int i = mapper.deleteById(id);
            if (i != 1) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该安全会议已经失效，请刷新页面!");
                factory.close(false);
                return msg;
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    /**
     * 解析 xlsx 后缀的excel文件
     *
     * @param file            xlsx 文件
     * @param startRowNumber  从第几行开始解析 （0开始）
     * @param startCellNumber 从第几列开始解析 （0开始）
     * @param stopCellNumber  解析列结束
     * @param keys  要解析的后 map 中的key，对应每列的数据
     * @return
     * @throws Exception
     */
    private List<Map> analysisXlsx(MultipartFile file, int startRowNumber,
                                   int startCellNumber, int stopCellNumber,
                                   List<String> keys) throws Exception {
        if (file == null && file.isEmpty()) {
            logger.error("上传文件为空");
            throw new NullPointerException("上传文件为空");
        }
        InputStream inputStream = file.getInputStream();
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        if (workbook == null) {
            logger.error("上传文件为空");
            throw new NullPointerException("上传文件为空");
        }
        XSSFSheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            logger.error("上传文件为空");
            throw new NullPointerException("上传文件为空");
        }
        List<Map> list = new LinkedList<>();
        Map map;
        XSSFRow row;
        for (int i = startRowNumber, countNum = sheet.getPhysicalNumberOfRows(); i < countNum; i++) {
            map = new HashMap();
            row = sheet.getRow(i);
            for (int j = startCellNumber; j <= stopCellNumber; j++){
                map.put(keys.get(j - startCellNumber), ExcelUtil.getCellValue(row.getCell(j)));
            }
            list.add(map);
        }
        return list;
    }
}
